package com.rtc.call.core

import android.content.Context
import android.media.MediaPlayer
import androidx.core.net.toUri
import java.io.IOException

class MediaPlayerManager(private val context: Context) {
    private var mMediaPlayer: MediaPlayer? = null

    fun createMediaPlayer() {
        mMediaPlayer = MediaPlayer()
        mMediaPlayer!!.setOnPreparedListener { obj: MediaPlayer -> obj.start() }
    }

    fun playerUrl(url: String) {
        if (mMediaPlayer == null) {
            createMediaPlayer()
        }
        try {
            mMediaPlayer!!.setDataSource(context, url.toUri())
            mMediaPlayer!!.isLooping = false
            mMediaPlayer!!.prepareAsync()
        } catch (e: IOException) {
            throw RuntimeException(e)
        }

    }
    fun stop() {
        mMediaPlayer?.stop()
    }

    fun releasePlayer() {
        mMediaPlayer?.let {
            it.stop()
            it.release()
            mMediaPlayer = null
        }
    }

}